import React, { useEffect, useState } from 'react';
import { StyleSheet, ScrollView } from 'react-native';
import sheet from '../../styles/sheet';
import colors from '../../styles/colors';
import Page from './Page';
import ButtonGroup from './ButtonGroup';

const TAB_BAR_HEIGHT = 70;

const styles = StyleSheet.create({
    buttonGroup: {
        backgroundColor: colors.secondary.white,
        height: TAB_BAR_HEIGHT,
        marginBottom: 0,
        marginLeft: 0,
        marginRight: 0,
        marginTop: 0,
    },
    scrollableButton: {
        paddingHorizontal: 24,
    },
});

export default function TabBarPage(props) {
    const [currentIndex, setCurrentIndex] = useState(props.initialIndex || 0);

    const buttonGroupProps = {
        selectedBackgroundColor: colors.primary.grayFaint,
        containerBorderRadius: 0,
        onPress: onOptionPress,
        selectedIndex: currentIndex,
        buttons: props.options.map((o) => o.label),
        containerStyle: styles.buttonGroup,
        scrollable: props.scrollable ? props.scrollable : false
    };

    function onOptionPress(index) {
        setCurrentIndex(index);
        console.log('点击#', index, typeof props.onOptionPress);
        if (typeof props.onOptionPress === 'function') {
            const option = props.options[index];
            props.onOptionPress(index, option.data);
        }
    }

    if (props.scrollable) {
        buttonGroupProps.buttonStyle = styles.scrollableButton;
    }

    return (
        <Page {...props}>
            {props.children}
            {props.scrollable ?
                (
                    <ScrollView horizontal style={{ maxHeight: TAB_BAR_HEIGHT }}>
                        <ButtonGroup {...buttonGroupProps} />
                    </ScrollView>
                ) : (
                    <ButtonGroup {...buttonGroupProps} />
                )}
        </Page>
    );
}